package com.soxing.braindata.service.interceptor;

import com.soxing.braindata.common.config.SystemConfig;
import com.soxing.braindata.domain.constants.SystemConstant;
import com.soxing.braindata.domain.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private SystemConfig systemConfig;

    /**
     * 目标方法执行前
     * 该方法在控制器处理请求方法前执行，其返回值表示是否中断后续操作
     * 返回 true 表示继续向下执行，返回 false 表示中断后续操作
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle{}", handler);
        String requestURI = request.getRequestURI();
        log.info("请求路径: {}, Handler: {}", requestURI, handler);

//        if (!systemConfig.isNeedLogin()) {
//            return true;
//        }

        HttpSession session = request.getSession();
        UserVo userVo = (UserVo) session.getAttribute(SystemConstant.LOGIN_USER);
        if (userVo == null) {
            //未登录
            response.setCharacterEncoding("UTF-8");
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "您没有权限进行此操作，请先登陆！");
            return false;
        } else {
            //放行
            return true;
        }
    }

    /**
     * 目标方法执行后
     * 该方法在控制器处理请求方法调用之后、解析视图之前执行
     * 可以通过此方法对请求域中的模型和视图做进一步修改
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle执行{}", modelAndView);
    }

    /**
     * 页面渲染后
     * 该方法在视图渲染结束后执行
     * 可以通过此方法实现资源清理、记录日志信息等工作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        log.info("afterCompletion执行异常{}", ex);
    }
}
